<template>
  <el-cascader
    ref="cascaderSelect"
    v-model="deptList"
    :show-all-levels="false"
    :options="deptTreeList"
    :disabled="disabled"
    :props="{
      emitPath:false,
      value: keyName,
      label: labelName,
      checkStrictly,
      multiple: multiple,
      children: 'children'
    }"
    :placeholder="placeholder"
    class="dept-select"
    size="small"
    collapse-tags
    filterable
    clearable
  >
    <template slot-scope="{ data }">
      <el-tooltip v-if="data.name.length > 14" placement="top-start" effect="dark">
        <div slot="content" style="max-width: 150px;">{{ data.name }}</div>
        <span class="inline-tag ellipsisOne">{{ data.name }}</span>
      </el-tooltip>
      <span v-else>{{ data.name }}</span>
    </template>
  </el-cascader>
</template>

<script>
import { getDepartmentAll } from '@/api/config';
import { mapState } from 'vuex';
// import { cascaderSoft } from '@/utils/tools';
export default {
  model: {
    prop: 'value',
    event: 'changeValue'
  },
  props: {
    value: {
      type: String | Array,
      default: ''
    },
    retrunArray: {
      type: Boolean,
      default: false
    },
    disabled: {
      type: Boolean,
      default: false
    },
    keyName: {
      type: String,
      default: 'name'
    },
    labelName: {
      type: String,
      default: 'name'
    },
    linkChildren: { // 点击父节点是否同步勾选其所有子节点
      type: Boolean,
      default: true
    },
    multiple: {
      type: Boolean,
      default: true
    },
    placeholder: {
      type: String,
      default: '请选择'
    },
    checkStrictly: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      deptTreeList: []
    };
  },
  computed: {
    ...mapState({
      'deptTree': state => state.user.deptTree,
      'showMobilePage': state => state.app.showMobilePage
    }),
    deptList: {
      get() {
        const value = this.value;
        if (!this.multiple || this.retrunArray) return value;
        if (value && value.length && value.length > 1) {
          return value.split(',');
        }
        return [];
      },
      set(newVal) {
        let value = newVal;
        if (this.multiple && !this.retrunArray) {
          value = newVal && newVal.length ? newVal.join(',') : '';
        }
        this.handelChange(value, this.value);
        // this.$emit('changeValue', value);
      }
    }
  },
  created() {
    if (this.deptTree && this.deptTree.length) {
      this.deptTreeList = this.deptTree;
    } else {
      this.queryDeptTreeList();
    }
  },
  methods: {
    handelChange(newVal, oldVal) {
      /**
       *  判断当前操作时勾选还是取消选中
       */
      let newArr = newVal;
      if (this.linkChildren && newArr) {
        const oldArr = oldVal || [];

        const curSelect = this.getDiff(newArr, oldArr); // 比较差异，获取到的就是当前选中的值
        if (curSelect) {
        /**
         * el-cascader 组件需要保证传进去的数组按照树形的顺序依次排序
         */
          if (newArr.length > 0 && typeof newArr === 'object') {
            const isSelect = newArr.length > oldArr.length;
            const node = this.$refs.cascaderSelect.panel.getNodeByValue(curSelect);
            const children = [];
            this.getTreeChildren(node, children);
            newArr = newArr.filter(i => !children.includes(i)); // 两个作用：1、如果是新增则为了原数组去重  2、如果是移除则同步删除子节点
            if (isSelect) {
              newArr.splice(newArr.indexOf(curSelect) + 1, 0, ...children); // 把新的数据加入进合适的位置（curSelect 的后面）
            }
          }
        }
      }
      this.$emit('changeValue', newArr);
    },
    getDiff(newArr, oldArr) {
      let ans = '';
      if (typeof newArr === 'object' && newArr.length > oldArr.length) {
        ans = newArr.filter(i => !oldArr.includes(i));
      } else if (typeof oldArr === 'object') {
        ans = oldArr.filter(i => !newArr.includes(i));
      }
      return ans && ans.length > 0 ? ans[0] : '';
    },
    getTreeChildren(node, ans) {
      if (node && node.children) {
        for (let i = 0; i < node.children.length; i++) {
          ans.push(node.children[i].data[this.keyName]);
          this.getTreeChildren(node.children[i], ans);
        }
      }
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        this.deptTreeList = (res && res.data) || [];
        // if (sort) cascaderSoft(this.paramsObj.cooperationDepartment, this.deptTreeList);
      }).catch(e => {
        console.log(e);
      });
    },
    getCheckedNodes() {
      return this.$refs.cascaderSelect.getCheckedNodes();
    }
  }
};
</script>

<style lang="scss" scoped>
.dept-select {
  &::v-deep {
    .el-tag.el-tag--info {
      color: #333;
      border-radius: 2px;
      background-color: #EFF3FB;
    }
    .el-cascader__tags {
      flex-wrap: nowrap;
      overflow: hidden;
    }
  }
}
</style>
